<template>
  <MkDialogEdit ref="dialogRef" v-model:isEdit="ctx.isEdit" @submit="submitFn">
    <MkForm :model="ctx.entity" ref="formRef" formId="basEnum">
      <MkInput label="枚举类型" v-model="ctx.entity.enumType" prop='enumType' :isEdit="false" :itemSpan="1" />
      <MkInput label="枚举值" v-model="ctx.entity.code" prop='code' :isEdit="ctx.isAdd" required :itemSpan="1" />
      <MkInput label="排序" v-model="ctx.entity.orderNo" prop='orderNo' :isEdit="ctx.isEdit" required type="number"
        :itemSpan="1" />
      <MkInput label="逻辑" v-model="ctx.entity.logic" prop='logic' :isEdit="ctx.isEdit" :itemSpan="1" />
      <MkInput label="备注" v-model="ctx.entity.remark" prop='remark' :isEdit="ctx.isEdit" :itemSpan="1" />
      <MkIsEnabled label="是否启用" v-model="ctx.entity.isEnabled" prop='isEnabled' :isEdit="ctx.isEdit" :itemSpan="1" />
    </MkForm>
  </MkDialogEdit>
</template>

<script lang='ts' setup>
import { BasEnumApi, BasEnum } from '/@/api/bas/basEnum';
import MkForm from '/@/componentsMaike/forms/MkForm.vue';
import { initBasEnumList } from '/@/stores/baseInfo/';
import { isNull, clog } from '/@/utils';

const emits = defineEmits(['query'])
const ctx = reactive({
  isAdd: false,
  isEdit: false,
  entity: {} as BasEnum,
});

const dialogRef = ref();
const formRef = ref<InstanceType<typeof MkForm>>();

/** 打开弹框 */
const openFn = async (row: BasEnum) => {
  dialogRef.value.show();
  if (isNull(row.code)) {
    ctx.isEdit = true;
    ctx.isAdd = true;
    ctx.entity = {
      enumType: row.enumType,
      code: '',
      orderNo: '',
      isEnabled: true,
    };
  } else {
    ctx.entity = row;
    ctx.isAdd = false;
    ctx.isEdit = false;
  }
};

const closeFn = () => {
  dialogRef.value?.close();
  emits('query')
};

const submitFn = async () => {
  if (!ctx.isEdit) {
    closeFn();
    return;
  }
  // 表单验证
  const validate = await formRef?.value?.validate();
  if (!validate) return;
  if (ctx.isAdd) {
    await BasEnumApi.add(ctx.entity);
  } else {
    await BasEnumApi.update(ctx.entity);
  }
  await initBasEnumList(true);
  closeFn();
};

defineExpose({ openFn })
</script>
